package com.huika.renrench.control.my.merchant;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.params.FileTypeParam;
import com.huika.lib.bitmap.core.ImageLoader;
import com.huika.lib.bitmap.core.ImageLoaderConfiguration;
import com.huika.lib.bitmap.core.assist.FailReason;
import com.huika.lib.bitmap.core.listener.ImageLoadingListener;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.dialog.MMAlert;
import com.huika.lib.utils.FileUtils;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.lib.utils.StringUtils;
import com.huika.lib.validation.EditTextValidator;
import com.huika.lib.validation.ValidationModel;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.login.validations.PhoneNumberValidation;
import com.huika.renrench.control.main.shoptf.gallery.ProductImageArray;
import com.huika.renrench.control.my.activity.ChoiceProvienceActivity;
import com.huika.renrench.control.my.certification.activity.WordsLengthFilter;
import com.huika.renrench.control.my.event.ImgDelEvent;
import com.huika.renrench.db.areainfo.AreaInfoDbHelper;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.support.bean.ShopTransferBean;
import com.huika.renrench.utils.FileTool;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.utils.ImageTools;
import com.huika.renrench.view.TitleBarHelper;
import com.huika.renrench.view.photos.Bimp;
import com.huika.renrench.view.photos.ImageGridAct;
import com.huika.renrench.view.photos.PhotoAct;
import com.huika.renrench.view.photos.PicSelectAct;
import com.huika.renrench.view.photos.PublicShowOrderGridAdapter;

import de.greenrobot.event.EventBus;
/**
 * @ClassName: MyShopActivity
 * @说明：转让新店铺
 * @author zwy
 * @date 2015年6月2日 下午5:48:41
 */
public class MyShopActivity extends BaseAct implements Listener<RequestResult<Object>>, MyLocationListener, OnFocusChangeListener {

	private GridView displayUploadPic_gv;// 显示上传图片的视图
	private LinearLayout addPic_layout;// 点击添加图片的按钮layout
	private ImageView addPic_img;// 添加图片的按钮

	private File picFile;
	private Dialog picDialog;
	private Context mContext;
	private static final int ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA = 3;
	public static ArrayList<String> imgUrlArray = new ArrayList<String>();
	private int count = -1;// 需要上传图片的张数
	private PublicShowOrderGridAdapter adapter;
	private String latitude;
	private String longitude;

	private EditText shop_name_detail;
	private EditText boss_name_detail;
	private EditText phone_detail;
	private EditText area_detail;
	private EditText rent_detail;
	private EditText address_detail;
	private EditText shop_intro_detail;
	private EditText near_detail;
	private EditText transfer_money_detail;
	private TextView province;
	private Button confirm;
	private int flag = -1;
	private static String shopId = "0";
	private ShopTransferBean shopTransferBean;
	private GaodeMapHelper gaodeMapHelper;
	private LocationBean locationBean;
	private String mAreaID = "";
	private boolean locationSuccess = false;
	private ImageView address_refresh;
	private String userId;
	private String phone;
	private StringBuffer sb = new StringBuffer();
	private ImageLoader imageLoader;
	private static String merchantId = "0";
	private TextView title_prompt;
	private boolean isClickRefresh;//是否点击刷新地址按钮
	private HashMap<String, String> map = new HashMap<String, String>();
	private ArrayList<String> removeList = new ArrayList<String>();
	private int removeCout = 0;
	private HashMap<String, Integer> imageMap = new HashMap<String, Integer>();//存放图片返回的位置
	

	private ArrayList<String> tDImgUrls = new ArrayList<String>();// 上传用的临时长地址,用于删除
	private HashMap<String, String> upDImgs = new HashMap<String, String>();// 上传用的id，<短地址,imgType>
	private HashMap<String, String> delImgs = new HashMap<String, String>();// 删除 <imageId,imageType>

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_my_shop_transfer);
		EventBus.getDefault().register(this);
		mContext = this;
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		super.onErrorResponse(error);
		error.printStackTrace();
		 confirm.setClickable(true);
	}

	@Override
	protected void initData() {
		super.initData();
		TitleBarHelper barHelper = new TitleBarHelper(this, -1);
		flag = getIntent().getIntExtra("flag", -1);
		shopId = getIntent().getStringExtra("shopId");
		merchantId = getIntent().getStringExtra("merchantId");
		userId = GlobalApp.userModel.getUserId();
		// phone = GlobalApp.userModel.getPhone();
		if (TextUtils.isEmpty(shopId)) {
			shopId = "0";
		} else {
			flag = 1;
		}
		if (TextUtils.isEmpty(merchantId)) {
			merchantId = "0";
		}
		if (flag == -1) {
			barHelper.setTitleMsg("店铺转让");
			barHelper.setLeftMsg("创业");

		} else {
			barHelper.setTitleMsg("编辑店铺转让信息");
			barHelper.setLeftMsg("返回");
			getShopStoreDetail(userId, shopId, 0d, 0d);
		}
	}

	private void updateOrAddShop(String userId, String shopAddress, String shopName, String mobile, String merchantId, String shopId, String merchantName, String latitude,
			String longitude, String nearby, String acreage, String areaId, String introduction, String imageId, String price, String transferAmount) {
		dismissLoadingDialog();
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("shopAddress", shopAddress);
		ajaxParams.putCommonTypeParam("shopName", shopName);
		ajaxParams.putCommonTypeParam("mobile", mobile);
		ajaxParams.putCommonTypeParam("shopId", shopId);
		ajaxParams.putCommonTypeParam("merchantName", merchantName);
		ajaxParams.putCommonTypeParam("merchantId", merchantId);
		ajaxParams.putCommonTypeParam("latitude", latitude);
		ajaxParams.putCommonTypeParam("longitude", longitude);
		ajaxParams.putCommonTypeParam("nearby", nearby);
		ajaxParams.putCommonTypeParam("areaId", areaId);
		ajaxParams.putCommonTypeParam("introduction", introduction);
		ajaxParams.putCommonTypeParam("imageId", imageId);
		ajaxParams.putCommonTypeParam("acreage", acreage);
		ajaxParams.putCommonTypeParam("price", price);
		ajaxParams.putCommonTypeParam("transferAmount", transferAmount);
		FormResultRequest<Object> request = new FormResultRequest<Object>(UrlConstants.UPDATEORADDSHOP, this, this, new TypeToken<RequestResult<Object>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	private String makeNewStr(String str) {
		String newStr = "";
		if (str.endsWith("万")) {
			newStr = str.substring(0, str.length() - 1);
			return (Double.parseDouble(newStr) * 10000) + "";
		}
		return str;
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				count--;
				if (count <= 0) {
					// confirm.setClickable(false);
					if(sb.length() == 0) {
						sb.append(",");
					}
					if (locationBean != null) {
						updateOrAddShop(userId, address_detail.getText().toString(), shop_name_detail.getText().toString(), phone_detail.getText().toString(), merchantId, shopId,
								boss_name_detail.getText().toString(), MoneyShowTool.twolastDF(locationBean.latitude), MoneyShowTool.twolastDF(locationBean.longtitude),
								near_detail.getText().toString(), area_detail.getText().toString(), mAreaID, shop_intro_detail.getText().toString(),
								sb.substring(0, sb.length() - 1), rent_detail.getText().toString(), transfer_money_detail.getText().toString());
					} else {
						updateOrAddShop(userId, address_detail.getText().toString(), shop_name_detail.getText().toString(), phone_detail.getText().toString(), merchantId, shopId,
								boss_name_detail.getText().toString(), MoneyShowTool.twolastDF(Double.parseDouble(latitude)),
								MoneyShowTool.twolastDF(Double.parseDouble(longitude)), near_detail.getText().toString(), area_detail.getText().toString(), mAreaID,
								shop_intro_detail.getText().toString(), sb.substring(0, sb.length() - 1), rent_detail.getText().toString(), transfer_money_detail.getText().toString());

					}
				}
			} else if (msg.what == 1) {
//				Timer timer = new Timer();
//				timer.schedule(new TimerTask() {
//
//					@Override
//					public void run() {
//						confirm.setClickable(true);
//					}
//				}, 5 * 1000);
			} else if(msg.what == 2) {
				removeCout--;
				if (removeCout <= 0) {
					uploadImg();
				}
			}
		};
	};

	private void uploadImgValidat(String validateKey, String fileName) {
		showLoadingDialog("上传中");
		try {
			FormResultRequest<HashMap<String, String>> request = new FormResultRequest<HashMap<String, String>>(UrlConstants.UPLOADIMG,
					new Listener<RequestResult<HashMap<String, String>>>() {

						@Override
						public void onResponse(RequestResult<HashMap<String, String>> arg0) {
							if (arg0.flag == 1) {
								sb.append(arg0.getRs().get("imageId"));
								sb.append(",");
								handler.sendEmptyMessage(0);

							} else {
								ToastMsg.showToastMsg(context, arg0.msg);
							}
						}
					}, this, new TypeToken<RequestResult<HashMap<String, String>>>() {
					}.getType());
			JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();//
			ajaxParams.putCommonTypeParam("userId", userId);// userId
			ajaxParams.putCommonTypeParam("validateKey", validateKey);
			ajaxParams.put(new FileTypeParam("fileName", fileName, FileUtils.getMimeType(Uri.fromFile(new File(fileName)).toString())));
			request.setRequestParams(ajaxParams);
			executeRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getShopStoreDetail(String userId, String shopId, double latitude, double longitude) {
		showLoadingDialog(getString(R.string.common_loading));
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("shopId", shopId);
		ajaxParams.putCommonTypeParam("latitude", latitude);
		ajaxParams.putCommonTypeParam("longitude", longitude);
		FormResultRequest<ShopTransferBean> request = new FormResultRequest<ShopTransferBean>(UrlConstants.GETSHOPSTOREDETAIL, new Listener<RequestResult<ShopTransferBean>>() {

			@Override
			public void onResponse(RequestResult<ShopTransferBean> arg0) {
				dismissLoadingDialog();
				if (arg0.flag == 1) {
					shopTransferBean = arg0.getRs();
					title_prompt.setVisibility(View.VISIBLE);
					if (shopTransferBean.checkStatus.equals("1")) {
						title_prompt.setText("您提交的店铺转让信息正在审核中，我们会在2天内完成审核，请耐心等待");
					} else if (shopTransferBean.checkStatus.equals("2")) {
						title_prompt.setText("您提交的店铺转让信息已经通过审核");
					} else if (shopTransferBean.checkStatus.equals("3")) {
						title_prompt.setText("您提交的店铺转让信息审核失败，失败原因：" + shopTransferBean.checkRemark);
					}
					address_detail.setText(shopTransferBean.address);
					if(TextUtils.isEmpty(shopTransferBean.changeType) || "null".equals(shopTransferBean.changeType) || "面议".equals(shopTransferBean.changeType)) {
						transfer_money_detail.setText("0");
					} else {
						transfer_money_detail.setText(MoneyShowTool.nolastDF(Double.parseDouble(shopTransferBean.changeType)));
					}
					if (!TextUtils.isEmpty(shopTransferBean.namePath) && !"null".equals(shopTransferBean.namePath)) {
						province.setText(getAreaName(shopTransferBean.namePath));
					} else {
						province.setText("选择省/市/区");
					}
					shop_name_detail.setText(shopTransferBean.getShopName());
					if (!TextUtils.isEmpty(shopTransferBean.name)) {
						boss_name_detail.setText(shopTransferBean.name);
					} else {
						boss_name_detail.setText("");
					}
					if (!TextUtils.isEmpty(shopTransferBean.shopId) && !shopTransferBean.shopId.equals("null")) {
						MyShopActivity.shopId = shopTransferBean.shopId;
					}
					if (!TextUtils.isEmpty(shopTransferBean.merchantId)) {
						MyShopActivity.merchantId = shopTransferBean.merchantId;
					}
					phone_detail.setText(shopTransferBean.getPhone());
					area_detail.setText(MoneyShowTool.nolastDF(shopTransferBean.getAcreage()));
					if(TextUtils.isEmpty(shopTransferBean.getPrice()) || shopTransferBean.getPrice().equals("null") || shopTransferBean.getPrice().equals("面议")) {
						rent_detail.setText("0");
					} else {
						rent_detail.setText(MoneyShowTool.nolastDF(Double.parseDouble(shopTransferBean.getPrice())));
						
					}
					if (!TextUtils.isEmpty(shopTransferBean.getIntroduction()) && !shopTransferBean.getIntroduction().equals("null")) {
						shop_intro_detail.setText(shopTransferBean.getIntroduction());
					} else {
						shop_intro_detail.setText("");
					}
					MyShopActivity.this.latitude = shopTransferBean.getLatitude();
					MyShopActivity.this.longitude = shopTransferBean.getLongitude();
					near_detail.setText(shopTransferBean.getNearby());
					mAreaID = shopTransferBean.areaId;
					shop_name_detail.setFilters(new InputFilter[]{new WordsLengthFilter(true, shop_name_detail, 40)});
					shop_intro_detail.setFilters(new InputFilter[]{new WordsLengthFilter(true, shop_intro_detail, 200)});
					setNetImage(shopTransferBean.getImageArray());
				}
			}
		}, this, new TypeToken<RequestResult<ShopTransferBean>>() {
		}.getType());
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}

	/**
	 * 
	 * @description：
	 * @author zc
	 * @date 2015年6月12日 下午3:45:17
	 */
	private String getAreaName(String namePath) {
		String newStr = "";
		if (namePath.indexOf("^中国") != -1) {
			newStr = namePath.substring(namePath.indexOf("^中国") + 3);
		}
		return newStr.replace("^", "");
	}

	private void checkInput() {
		if (shop_name_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入店铺名称");
			return;
		} else if (boss_name_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入老板名字");
			return;
		} 
		else if(phone_detail.length() != 11) {
			ToastMsg.showToastMsg(this, "请输入正确的手机号");
			return;
		}
		else if (area_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入店铺面积");
			return;
		} else if (rent_detail.length() == 0) {
//			ToastMsg.showToastMsg(this, "请输入店铺租金");
//			return;
			rent_detail.setText("0");
		} 
		else if (address_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入店铺地址");
			return;
		} else if (shop_intro_detail.length() == 0) {
			ToastMsg.showToastMsg(this, "请输入店铺简介");
			return;
		} else if (province.getText().toString().contains("选择省/市/区")) {
			ToastMsg.showToastMsg(this, "请选择区域");
			return;
		} else if (Bimp.drr.size() < 4) {
			ToastMsg.showToastMsg(this, "请上传不少于3张图片");
			return;
		} 
		
		if(transfer_money_detail.length() == 0) {
//			ToastMsg.showToastMsg(this, "请输入转让费");
//			return;
			transfer_money_detail.setText("0");
		}
		confirm.setClickable(false);
//		handler.sendEmptyMessage(1);
		if(removeList.size() == 0) {
			uploadImg();
		} else {
			removeCout = removeList.size();
			for(int i =0; i < removeList.size(); i++) {
				delNet(userId, removeList.get(i), shopId);
			}
		}
	}
	
	private void uploadImg() {
		try {
			if(Bimp.drr.contains("")) {
				count = Bimp.drr.size() - 1;
			} else {
				count = Bimp.drr.size();
			}
			for (int i = 0; i < Bimp.drr.size(); i++) {
				if(!TextUtils.isEmpty(Bimp.drr.get(i))) {
					if(!Bimp.drr.get(i).contains(FileTool.getDefaultfoldername())) {
						uploadImgValidat(FileTool.getMD5FromFile(new File(Bimp.drr.get(i))), Bimp.drr.get(i));
					} else {
						sb.append(map.get(Bimp.drr.get(i))).append(",");
						handler.sendEmptyMessage(0);
					}
				}
//				if (!TextUtils.isEmpty(Bimp.drr.get(i)))
//					uploadImgValidat(FileTool.getMD5FromFile(new File(Bimp.drr.get(i))), Bimp.drr.get(i));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		displayUploadPic_gv = (GridView) findViewById(R.id.display_upload_pic);
		addPic_layout = (LinearLayout) findViewById(R.id.add_pic_layout);
		addPic_img = (ImageView) findViewById(R.id.add_pic);
		shop_name_detail = (EditText) findViewById(R.id.shop_name_detail);
		boss_name_detail = (EditText) findViewById(R.id.boss_name_detail);
		phone_detail = (EditText) findViewById(R.id.phone_detail);
		area_detail = (EditText) findViewById(R.id.area_detail);
		rent_detail = (EditText) findViewById(R.id.rent_detail);
		address_detail = (EditText) findViewById(R.id.address_detail);
		shop_intro_detail = (EditText) findViewById(R.id.shop_intro_detail);
		near_detail = (EditText) findViewById(R.id.near_detail);
		confirm = (Button) findViewById(R.id.confirm);
		province = (TextView) findViewById(R.id.province);
		address_refresh = (ImageView) findViewById(R.id.address_refresh);
		title_prompt = (TextView) findViewById(R.id.title_prompt);
		transfer_money_detail = (EditText) findViewById(R.id.transfer_money_detail);
		area_detail.setOnFocusChangeListener(this);
		rent_detail.setOnFocusChangeListener(this);
		if(flag == -1) {
			shop_name_detail.setFilters(new InputFilter[]{new WordsLengthFilter(true, shop_name_detail, 40)});
			shop_intro_detail.setFilters(new InputFilter[]{new WordsLengthFilter(true, shop_intro_detail, 200)});
		}
		
		phoneValidator = new EditTextValidator(this).add(new ValidationModel(phone_detail, new PhoneNumberValidation())).execute();
		phone_detail.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() > 0) {
					if (!s.toString().substring(0, 1).equals("1")) {
						phone_detail.setText("");
					} else if (s.length() > 1 && !s.toString().substring(1, 2).matches("[345789]")) {
						phone_detail.setText("1");
						phone_detail.setSelection(phone_detail.length());
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		// phone_detail.setText(phone);
		addPic_img.setOnClickListener(this);
		adapter = new PublicShowOrderGridAdapter(this);
		displayUploadPic_gv.setAdapter(adapter);
		displayUploadPic_gv.setOnItemClickListener(myClickListener);
		confirm.setOnClickListener(this);
		gaodeMapHelper = new GaodeMapHelper(this);
		gaodeMapHelper.setmLocationListener(this);
		province.setOnClickListener(this);
		address_refresh.setOnClickListener(this);
		shop_intro_detail.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				shop_intro_detail.getParent().requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});
		if (flag == -1) {
			gaodeMapHelper.start();
		}
		// showToastMsg("定位中...");

	}

	@Override
	public void onBackPressed() {
		gaodeMapHelper.stop();
		super.onBackPressed();
	}

	@Override
	public void widgetClick(View v) {
		switch (v.getId()) {
		case R.id.add_pic:
			addPic();
			break;
		case R.id.confirm:
			checkInput();
			break;
		case R.id.province:
			Intent areaIntent = new Intent(this, ChoiceProvienceActivity.class);
			startActivityForResult(areaIntent, 10000);
			break;
		case R.id.address_refresh:
			isClickRefresh = true;
			gaodeMapHelper.start();
			// showToastMsg("定位中...");
			break;
		default:
			break;
		}
	}

	private void addPic() {
		if (picDialog == null) {
			picDialog = MMAlert.createTwoChoicAlertNoTitle(this, R.string.common_camera, R.string.common_gallery, new MMAlert.DialogOnItemClickListener() {

				@Override
				public void onItemClickListener(View v, int position) {
					int id = v.getId();
					switch (id) {
					case R.id.item_first:
						if (!ImageTools.isSDCardExist()) {
							ToastMsg.showToastMsg(mContext, "sd卡不可用");
							return;
						}
						Intent cameraIntent = null;
						picFile = ImageTools.initTempFile();
						cameraIntent = ImageTools.getTakeCameraIntent(Uri.fromFile(picFile));
						startActivityForResult(cameraIntent, ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA);
						picDialog.dismiss();
						break;

					case R.id.item_second:
						Intent photoIntent = null;
						if(MyProgramActivity.imgUrlArray != null && MyProgramActivity.imgUrlArray.size() > 0) {
							MyProgramActivity.imgUrlArray.clear();
						}
						photoIntent = new Intent(mContext, PicSelectAct.class);
						photoIntent.putExtra(ImageGridAct.EXTRA_IMAGE_NUM, 10);
						mContext.startActivity(photoIntent);
						break;
					}
				}

			});
		}
		picDialog.show();
	}
	
	private EditTextValidator phoneValidator;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case ACTIVITY_RESULT_NO_CROPCAMARA_WITH_DATA:
			if (Bimp.drr.size() < 10 && picFile != null || picFile.exists()) {
				String cameraImgPath = picFile.getAbsolutePath();
				// 重新把bitmap型变成File；
				picFile = ImageTools.saveImgForUpload(cameraImgPath);
				Bimp.drr.add(picFile.getPath());
				imgUrlArray.add(picFile.getPath());
			}
			break;
		case REQ_CODE_SELECT_AREA:
			int areaId = data.getIntExtra("CHOICE_AREA_RESULT_ID", -1);
			if(areaId == -1) {
				ToastMsg.showToastMsg(this, "区域选择失败，请重新选择");
				return;
			}
			mAreaID = areaId == -1 ? "" : (areaId + "");
			// mShopTransferBean.shopAdress =
			// data.getStringExtra("CHOICE_AREA_RESULT");
			province.setText(data.getStringExtra("CHOICE_AREA_RESULT").replace(" ", "").replace("中国", ""));
			break;
		}

	}

	public final int REQ_CODE_SELECT_AREA = 10000;

	private OnItemClickListener myClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			if (arg0.getChildCount() - 1 == arg2 && (arg0.getChildCount() != 10 || count == 9)) {
				addPic();
			} else {
				Intent intent = new Intent(MyShopActivity.this, PhotoAct.class);
				intent.putExtra("ID", arg2);
				startActivity(intent);
			}
		}
	};
	
	private void delNet(String userId, String imgId, String shopId) {
		showLoadingDialog("删除中...");
		FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.DELETIMAGE, delistener, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError arg0) {
			}
		}, new TypeToken<RequestResult<String>>() {
		}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
		ajaxParams.putCommonTypeParam("type", 5);
		ajaxParams.putCommonTypeParam("imageId", imgId);
		ajaxParams.putCommonTypeParam("userId", userId);
		ajaxParams.putCommonTypeParam("shopId", shopId);
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	private Listener<RequestResult<String>> delistener = new Listener<RequestResult<String>>() {
		@Override
		public void onResponse(RequestResult<String> arg0) {
			dismissLoadingDialog();
			handler.sendEmptyMessage(2);
		}
	};

	@Override
	protected void onRestart() {
		super.onRestart();
		if (Bimp.drr != null) {
			Bimp.drr.remove("");
			count = Bimp.drr.size();
			if (Bimp.drr != null && Bimp.drr.size() > 0) {
				addPic_layout.setVisibility(View.GONE);
				displayUploadPic_gv.setVisibility(View.VISIBLE);
				if (Bimp.drr.size() < 10) {
					Bimp.drr.add("");
				}
				adapter.setGroup(Bimp.drr);
			} else {
				addPic_layout.setVisibility(View.VISIBLE);
				displayUploadPic_gv.setVisibility(View.GONE);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		imgUrlArray.clear();
		Bimp.drr.clear();
		if (MyProgramActivity.imgUrlArray != null) {
			MyProgramActivity.imgUrlArray.clear();
		}
	}

	@Override
	public void onResponse(RequestResult<Object> arg0) {
		dismissLoadingDialog();
		if (arg0.flag == 1) {
			Intent intent = new Intent(this, SubmitSuccessActivity.class);
			intent.putExtra("succesTip", "提交店铺转让信息成功");
			intent.putExtra("succesPrompt", "我们会在2天内完成项目审核，通过后您的店铺转让信息将会展现在店铺转让列表。");
			showActivity(this, intent);
			finish();
			FileTool.clear(new File(FileTool.getDefaultfoldername()));
		} else {
			// confirm.setClickable(true);
		}
	}

	/**
	 * 检查定位，查找区域id并展示结果
	 * 
	 * @param showError
	 * @return
	 * @author FAN 创建于Mar 19, 2015
	 */
	AreaInfoDbHelper areaInfoDbHelper;

	private boolean checkLocationError(boolean showError) {
		if (locationBean == null || TextUtils.isEmpty(locationBean.province)) {
			if (showError) {
				showToastMsg("定位失败");
			}
			return true;
		} else {
			if (flag == -1 || isClickRefresh) {
				province.setText(locationBean.toShortAddress());
				address_detail.setText(locationBean.getDetailAddress());
				isClickRefresh = false;
			} else {

			}
			// 查找区域id areaId
			if (areaInfoDbHelper == null) {
				areaInfoDbHelper = new AreaInfoDbHelper();
			}
			String namePath = locationBean.province + "^" + locationBean.city + "^" + locationBean.district;
			if(areaInfoDbHelper.getAreaIDByNamePath(namePath) == -1) {
				ToastMsg.showToastMsg(this, "获取区域id失败");
			} else {
				mAreaID = "" + areaInfoDbHelper.getAreaIDByNamePath(namePath);
			}
			locationSuccess = true;
			return false;
		}
	}
	
	public void onEventMainThread(ImgDelEvent delEvent) {
//		switch (delEvent.getType()) {
//		case 1:
//			upDImgs.remove(FileTool.getFileName(tDImgUrls.get(delEvent.getIndex())));
//			tDImgUrls.remove(delEvent.getIndex());
//			break;
//		case 2:
//			upZImgs.remove(FileTool.getFileName(tZImgUrls.get(delEvent.getIndex())));
//			tZImgUrls.remove(delEvent.getIndex());
//			break;
//		case 3:
//			upXImgs.remove(FileTool.getFileName(tXImgUrls.get(delEvent.getIndex())));
//			tXImgUrls.remove(delEvent.getIndex());
//			break;
//
//		default:
//			break;
//		}
		if(map.containsKey(delEvent.getPath())) {
			removeList.add(map.remove(delEvent.getPath()));
		}
	}


	@Override
	public void onLocation(LocationBean locationBean) {
		this.locationBean = locationBean;
		checkLocationError(true);
		gaodeMapHelper.stop();
		// if(flag != -1 && !isClickRefresh) {
		// getShopStoreDetail(userId, shopId, locationBean.latitude,
		// locationBean.longtitude);
		// isClickRefresh = false;
		// }
	}

	private void setNetImage(ArrayList<ProductImageArray> imgs) {
		for (int i = 0; i < imgs.size(); i++) {
			imageMap.put(imgs.get(i).getImageUrl(), Integer.valueOf(i));
			final String url = imgs.get(i).getImageUrl();
			final String imageId = imgs.get(i).imageID;
			imgUrlArray.add(i + "");
			Bimp.drr.add(i + "");
			imageLoader.loadImage(url, new ImageLoadingListener() {
				@Override
				public void onLoadingStarted(String arg0, View arg1) {

				}

				@Override
				public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {

				}

				@Override
				public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
					try {
						// File file = imageLoader.getDiskCache().get(url);
//						imgUrlArray.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
//						Bimp.drr.add(String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
						if(imgUrlArray != null && imgUrlArray.size() > 0 && Bimp.drr != null && Bimp.drr.size() > 0) {
							FileTool.saveFile(arg2, FileTool.getFileName(arg0), "");
							imgUrlArray.set(imageMap.get(url), String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
							Bimp.drr.set(imageMap.get(url), String.format("%s/%s", FileTool.getDefaultfoldername(), FileTool.getFileName(arg0)));
							map.put(FileTool.getDefaultfoldername() + "/" + FileTool.getFileName(arg0), imageId);
							onRestart();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onLoadingCancelled(String arg0, View arg1) {

				}
			});
		}
	}

	private void makeNewStr(EditText editText, String str) {
		if (str.endsWith("万")) {
			editText.setText(Double.parseDouble(str.substring(0, str.length() - 1)) * 10000 + "");
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		switch (v.getId()) {
		case R.id.area_detail:
//			if (hasFocus) {
//				makeNewStr(area_detail, area_detail.getText().toString());
//			}
			break;
		case R.id.rent_detail:
//			if (hasFocus) {
//				makeNewStr(rent_detail, rent_detail.getText().toString());
//			}
			break;
		default:
			break;
		}
	}

}
